package com.bgl.mall.exception;

import com.bgl.mall.common.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author buguoliang
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
	/**
	 * validation Exception
	 * @param exception
	 * @return ServerResponse
	 */
	@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public ServerResponse bodyValidExceptionHandler(MethodArgumentNotValidException exception) {
		List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
		log.warn(fieldErrors.get(0).getDefaultMessage());
		log.info("*******************请求异常*******************");
		log.error("参数校验异常信息：{}", fieldErrors.get(0).getDefaultMessage());
		return ServerResponse.createByErrorMessage(fieldErrors.get(0).getDefaultMessage());
	}

	/**
	 * 全局异常.
	 * @param e the e
	 * @return ServerResponse
	 */
	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public ServerResponse exceptionHandler(Exception e) {
		log.info("*******************请求异常*******************");
		log.error("全局异常信息：{}", e);
		return ServerResponse.createByErrorMessage(e.getMessage());
	}
}
